package be.dch.gui.components;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;

public class JTextFieldBrowse implements ActionListener {

    /**
     * ActionCommand for the Browse button.
     */
    public static String cmdBrowse = "browse";

    private final transient JLabel label;
    private final transient JTextField textField;
    private final transient JButton button;
    private final transient JComponent parent;
    private final transient int selectionMode;
    private transient javax.swing.filechooser.FileFilter filter;

    /**
     * 
     * @param label
     * @param parent
     * @param selectionMode
     */
    public JTextFieldBrowse(final String label, final JComponent parent, final int selectionMode) {
	super();
	this.label = new JLabel(label);
	this.textField = new JTextField();
	this.label.setLabelFor(this.textField);
	this.button = new JButton("Browse");
	this.button.setActionCommand(JTextFieldBrowse.cmdBrowse);
	this.button.addActionListener(this);
	this.parent = parent;
	this.selectionMode = selectionMode;
    }

    public JLabel getLabel() {
	return this.label;
    }

    public JTextField getTextField() {
	return this.textField;
    }

    public JButton getButton() {
	return this.button;
    }

    public void setFileFilter(final FileFilter filter) {
	this.filter = filter;
    }

    public void actionPerformed(final ActionEvent evt) {
	if (evt.getActionCommand() == JTextFieldBrowse.cmdBrowse) {
	    final JFileChooser chooser = new JFileChooser();
	    chooser.setFileSelectionMode(this.selectionMode);
	    if (this.filter != null) {
		chooser.setFileFilter(this.filter);
	    }
	    final int result = chooser.showOpenDialog(this.parent);
	    if (result == 0) {
		this.textField.setText(chooser.getSelectedFile().getAbsolutePath());
	    }
	}

    }

    public String getText() {
	return this.textField.getText();
    }

    public void addActionListener(final ActionListener listener) {
	this.button.addActionListener(listener);
    }

}
